<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole"> 添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolelist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag @close="remveRightById(scope.row, item1.id)" closable>{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="remveRightById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      :class="['vcenter']"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      @close="remveRightById(scope.row, item3.id)"
                      closable
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre>
              <!-- {{ scope.row }} -->
            </pre>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="setRoled(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="delRole(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-settig"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogColsed"
    >
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoledialogVisible"
      width="50%"
      @close="addRoleColse"
    >
      <p>
        角色名称：<el-input v-model="roleName" autocomplete="off"></el-input>
      </p>
      <p>
        角色描述：<el-input v-model="roleDesc" autocomplete="off"></el-input>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoletrue">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="setRoledDialogVisible"
      width="50%"
    >
      <div>
        <p>
          角色名称：<el-input
            v-model="setroleName"
            autocomplete="off"
          ></el-input>
        </p>
        <p>
          角色描述：<el-input
            v-model="setroleDesc"
            autocomplete="off"
          ></el-input>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoledTrue">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除角色对话框 -->
    <el-dialog
      title="删除角色"
      :visible.sync="delRoledialogVisible"
      width="50%"
    >
      <span>确定永久删除：{{ delRoleName }} 该角色吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delRoleTrue">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  watch: {},
  data() {
    return {
      // 所有角色列表数据
      rolelist: [],
      // 控制分配权限对话框显示与隐藏
      setRightDialogVisible: false,
      rightslist: [],
      //树形控件的属性绑定对象    将获取的数据和树形结构的数据联系起来
      treeProps: {
        label: 'authName', // 字段名
        children: 'children', // 子对象名
      },
      // 默认选中的节点id属性
      defKeys: [],
      // 当前即将分配权限的roleId
      roleId: '',
      // 控制添加角色对话框1
      addRoledialogVisible: false,
      // 角色名称
      roleName: '',
      // 角色描述
      roleDesc: '',
      // 控制编辑角色对话框
      setRoledDialogVisible: false,
      // 保存编辑角色的id
      setId: '',
      // 角色名称
      setroleName: '',
      // 角色描述
      setroleDesc: '',
      // 控制删除角色对话框
      delRoledialogVisible: false,
      // 要删除的角色名称
      delRoleName: '',
      // 要删除的角色id
      delRoleId: '',
    }
  },
  created() {
    this.getRolesLise()
  },
  methods: {
    // 获取所有角色列表
    async getRolesLise() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolelist = res.data
      console.log((this.rolelist = res.data))
    },
    // 根据id删除对应的权限
    async remveRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }

      console.log('确认删除')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除权限失败')
      }
      // this.getRolesLise()
      // 重新赋值一下数据，不要重新调用数据获取的方法，可以让页面不刷新更新数据
      role.children = res.data
    },
    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      this.setRightDialogVisible = true
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys)

      // 获取到的权限数据保存到data中
      this.rightslist = res.data
      // console.log(this.rightslist)
    },
    // 通过递归的形式获取角色下所有三级权限的id，并保存到defkeys 数组中
    getLeafKeys(node, arr) {
      // 如果当前node不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 调用遍历数组，将node中的children遍历，得到三级节点
      node.children.forEach((item) => this.getLeafKeys(item, arr))
    },
    // 监听权限分配对话框关闭事件  每次关闭分配权限对话框时，对defkeys数组进行清空
    setRightDialogColsed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),

        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(11)
      // console.log(keys)
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status != 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesLise()
      this.setRightDialogVisible = false
    },
    // 添加角色
    addRole() {
      this.addRoledialogVisible = true
    },
    // 提交添加角色
    async addRoletrue() {
      const { data: res } = await this.$http.post('roles', {
        roleName: this.roleName,
        roleDesc: this.roleDesc,
      })
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败！')
      }
      this.$message.success('添加角色成功！')
      // 刷新数据
      this.getRolesLise()
      this.addRoledialogVisible = false
    },
    // 监听添加角色对话框关闭事件，重置输入的数据
    addRoleColse() {
      this.roleName = ''
      this.roleDesc = ''
    },

    // 监听编辑角色对话框
    setRoled(roled) {
      this.setroleName = roled.roleName
      this.setroleDesc = roled.roleDesc
      this.setId = roled.id
      this.setRoledDialogVisible = true
    },
    // 编辑角色请求
    async setRoledTrue() {
      console.log(this.setId)
      if (this.setroleName === '') {
        return this.$message.error('角色名称不能为空')
      }
      const { data: res } = await this.$http.put('roles/' + this.setId, {
        roleName: this.setroleName,
        roleDesc: this.setroleDesc,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('编辑角色失败！')
      }
      this.$message.success('编辑角色成功！')
      // 刷新数据
      this.getRolesLise()
      this.setRoledDialogVisible = false
    },
    // 删除角色对话框
    delRole(role) {
      // console.log(role.id)
      this.delRoleName = role.roleName
      this.delRoleId = role.id
      this.delRoledialogVisible = true
    },
    // 确认删除角色事件
    async delRoleTrue() {
      // console.log(this.delRoleId)
      const { data: res } = await this.$http.delete('roles/' + this.delRoleId)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      // 刷新数据
      this.getRolesLise()
      this.delRoledialogVisible = false
    },
  },
}
</script>

<style>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>